package com.husd.framework.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/1/22 9:15 下午
 */
public class ScatteringExample {

    public static void main(String[] args) throws IOException {

        String path = "/tmp/a.txt";
        File f = new File(path);
        if (!f.exists()) {
            f.createNewFile();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(f, "r");
        FileChannel channel = randomAccessFile.getChannel();
        //channel.position(channel.size());

        //把多个buffer的数据，写入到channel中
        ByteBuffer header = ByteBuffer.allocate(3 * 4);
        header.clear();
        ByteBuffer body = ByteBuffer.allocate(8);
        body.clear();

        ByteBuffer[] bufferArray = {header, body};
        long read = channel.read(bufferArray);

        CharsetDecoder charsetDecoder = Charset.forName("utf-8").newDecoder();

        while (read != -1) {
            header.flip();
            body.flip();
            System.out.println("---------- header");
            while (header.hasRemaining()) {
                System.out.print(header.getInt());
            }
            header.clear();
            System.out.println("---------- body");
            while (body.hasRemaining()) {
                System.out.print(body.getChar());
            }
            body.clear();
            read = channel.read(bufferArray);
        }
    }
}
